package com.cennavi.opers;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cennavi.dbs.MongoPool;
import com.cennavi.dbs.ZooKeeperConfigs;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

import net.sf.json.JSONObject;

public class TextExport extends HttpServlet {
 

	/**
	 * 
	 */
	private static final long serialVersionUID = -7711113762304586380L;

	public TextExport() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");

		PrintWriter out = response.getWriter();

		try {

			JSONObject json = JSONObject.fromObject(request
					.getParameter("request"));

			String taskIds = json.getString("task_ids");
			
//			String paths = json.getString("save_paths");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String taskId = "task_" + sdf.format(new Date());
			String sourceNames = json.getString("names");

//			DBCollection collection = MongoPool.getDB().getCollection(
//					"data_export");
//
//			DBCursor cursor = collection.find(
//					(DBObject) JSON.parse("{'task_id':'" + taskId + "'}"),
//					(DBObject) JSON.parse("{'_id':" + 0 + "}"));
//
//			if (cursor.hasNext()) {
//				DBObject obj = cursor.next();
//
//				int status = (int) obj.get("status");
//
//				if (status == 1) {
//					// 进行中
//					out.println("{\"error_code\":0,\"error_msg\":\"\",\"progress\":\"20%\"}");
//
//				} else {
//					// 完成
//					String ftp_ip = ZooKeeperConfigs.props
//							.getProperty("ftp_ip_public");
//					String ftp_username = ZooKeeperConfigs.props
//							.getProperty("ftp_username");
//					String ftp_password = ZooKeeperConfigs.props
//							.getProperty("ftp_password");
//					String ftp_port = ZooKeeperConfigs.props
//							.getProperty("ftp_port");
//					out.println("{\"error_code\":0,\"error_msg\":\"\",\"url\":\""
//							+ ftp_ip +"\",\"file_name\":\""+taskId
//							+ "\",\"user\":\""
//							+ ftp_username
//							+ "\",\"password\":\"" + ftp_password + "\",\"port\":"+ftp_port+"}");
//
//				}
//			} else {
				// 进行导出
				StringBuilder sb = new StringBuilder(
						"spark-submit --master yarn --num-executors "
								+ 50
								+ " --executor-memory 8500m --class com.cennavi.engine.file2ftp --name lunch --jars /var/lib/hadoop-hdfs/lilei/tools.jar,/var/lib/hadoop-hdfs/lilei/spark-csv_2.11-1.3.2.jar,/var/lib/hadoop-hdfs/lilei/commons-csv-1.1.jar /var/lib/hadoop-hdfs/lilei/engine-a.jar ");

				sb.append(taskIds);
//				sb.append(" ");
//				sb.append(paths);
				sb.append(" ");
				sb.append(ZooKeeperConfigs.props.get("ftp_ip_private"));
				sb.append(" ");
				sb.append(ZooKeeperConfigs.props.get("ftp_username"));
				sb.append(" ");
				sb.append(ZooKeeperConfigs.props.get("ftp_password"));
				sb.append(" ");
				sb.append(taskId);
				sb.append(" ");
				sb.append(sourceNames);

				final String cmd = sb.toString();

				scala.io.Source.fromURL(
						"http://10.20.20.11:8080/maven-web/opers?param="
								+ URLEncoder.encode(cmd, "UTF-8"), "UTF-8");
				
				out.println("{\"error_code\":0,\"error_msg\":\"\",\"progress\":\"20%\"}");
//			}

		} catch (Exception e) {

			e.printStackTrace();

			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
